<!-- 诊断项症状 -->
<template>
  <div>
    <ContainerSlot>
      <template slot="searchModule">
        <SearchForm :label-width="labelWidth" :form-config="formConfig" :form-data="formData" :slot-list="slotList">
          <template slot="searchform">
            <el-form :inline="true" :model="searchForm">
              <el-form-item label="诊断项名称：" :label-width="formLabelWidth" prop="diagnosisItemName">
                <el-select v-model="searchForm.diagnosisItemId" placeholder="请选择" clearable>
                  <el-option v-for="item of diagnosisItemName" :key="item.diagnosisItemId" :label="item.diagnosisItemName" :value="item.diagnosisItemId" />
                </el-select>
              </el-form-item>
              <el-form-item label="诊断项症状编号：" :label-width="formLabelWidth" prop="diagnosisItemSymbolNo">
                <el-input v-model="searchForm.diagnosisItemSymbolNo" placeholder="请输入" clearable></el-input>
              </el-form-item>
            </el-form>
          </template>
          <template slot="searchBtn">
            <el-button type="primary" @click.prevent="search()">
              查询
            </el-button>
          </template>
        </SearchForm>
      </template>

      <template slot="operationModule">
        <el-button type="primary" @click="add">添加</el-button>
        <el-button type="danger" @click="delSelectData"> 删除 </el-button>
      </template>

      <template slot="contentModule">
        <Table :prop-list="propList" :list-data="tableData" @handleSelectionChange="handleSelectionChange">
          <template slot="featureImage" slot-scope="{ row }">
            <el-button v-if="row.diagnosisItemName" type="primary" plain @click="rowimg(row.fileIdList)">
              查看图片
            </el-button>
          </template>
          <template slot="operation" slot-scope="{ row }">
            <el-button class="opt" type="primary" v-show="row.diagnosisItemId" plain @click="edit(row)">
              <i class="el-icon-edit-outline"></i>编辑
            </el-button>
            <el-button class="opt" type="danger" v-show="row.diagnosisItemId" plain @click="del(row)">
              <i class="el-icon-delete"></i>删除
            </el-button>
          </template>
        </Table>
      </template>
      <!-- 分页器 -->
      <template slot="footerModule">
        <el-pagination :current-page="currentPage" background :page-size="pageSize" :page-sizes="[10, 20, 30]"  
          layout=" prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </template>
    </ContainerSlot>

    <!-- 添加/修改 对话框 -->
    <el-dialog :close-on-click-modal="false" :title="`疾病特征${title}`" 
      :visible.sync="dialogFormVisible" top="30vh" @close="cancle" :modal="false">
      <!-- 表单收集 -->
      <el-form ref="ruleForm" :inline="true" :model="toForm" :rules="rules">
        <el-form-item label="诊断项名称：" :label-width="formLabelWidth" prop="diagnosisItemId">
          <el-select v-model="toForm.diagnosisItemId" placeholder="请选择" clearable>
            <el-option v-for="item of diagnosisItemName" 
              :key="item.diagnosisItemId" 
              :label="item.diagnosisItemName" 
              :value="item.diagnosisItemId" />
          </el-select>
        </el-form-item>

        <el-form-item label="诊断项症状编号：" :label-width="formLabelWidth" prop="diagnosisItemSymbolNo">
          <el-input v-model="toForm.diagnosisItemSymbolNo" placeholder="请输入"></el-input>
        </el-form-item>

        <el-form-item label="特征描述：" :label-width="formLabelWidth" prop="diagnosisItemSymbolDesc" class="aTextarea">
          <el-input v-model="toForm.diagnosisItemSymbolDesc" clearable type="textarea" 
            :rows="3" style="width:100%" placeholder="" show-word-limit maxlength="127" />
        </el-form-item>
        <br />

        <!-- 添加图片 -->
        <el-form-item label="特征图片" :label-width="formLabelWidth" prop="fileIdList" class="tzImg">
          <el-upload ref="upload" 
            action="http://fishery.ssagroup.cn:9091/socialized-expert/files/upload" 
            list-type="picture-card" 
            :file-list="fileList" 
            :on-success="onSuccessImg" 
            :on-remove="handleRemove" 
            :on-preview="handlePictureCardPreview" 
            :on-change="handleChange" 
            :headers="MyHeader">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <!-- 大图预览 -->
        <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" :modal="false" :modal-append-to-body="false">
          <img width="100%" :src="dialogImageUrl" alt="" style="width:'100%'" />
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
    <!-- 查看特征图片 -->
    <el-dialog :close-on-click-modal="false" title="特征图片" :visible.sync="featureImage" 
      :width="dialogWidth" :modal="false" :modal-append-to-body="false">
      <el-image v-for="(item,index) in imageList" :key="index" :src="item" 
        :preview-src-list="imageList" class="image-item" style="width: 100px; height: 100px" >
      </el-image>
    </el-dialog>
  </div>
</template>

<script>
import ContainerSlot from "@/components/Container";
import SearchForm from "./components/form.vue";
import Table from "@/components/Table";
import Upload from "./components/upload.vue";   // upload上传
import newDocumentApi from "@/api/newdocument"; // 图片上传/下载
import config from "@/api/config";
import { blobToBase64 } from "./components/convert";

import DiseaseFeaturesManageApi from "@/api/disease-bank-manage/disease-features-manage/index";  // 诊断项症状
import FeaturesTypeManageApi from "@/api/disease-bank-manage/features-type-manage/index";        // 诊断项

// 获取本地cookie
const getCookie = function (name) {
  let arr = document.cookie.split("; ");
  for (let value of arr) {
    let newarr = value.split("=");
    if (name === newarr[0]) {
      return newarr[1];
    }
  }
};
console.log(getCookie("token"));

export default {
  name: "",
  components: { ContainerSlot, SearchForm, Table, Upload },
  data() {
    // var validateAttach = (rule, value, callback) => {
    //   if (!this.toForm.fileIdList) {
    //     return callback(new Error("请上传一张图片"));
    //   } else {
    //     return callback();
    //   }
    // };
    return {
      // 查询栏 - 表单配置
      formConfig: [],
      // 查询栏 - 表单数据
      formData: {
        diagnosisItemName: "",
        diagnosisItemSymbolNo: "",
      },
      // 查询区域插槽
      slotList: [
        {slotName: "searchBtn",},
      ],
      // 搜索表单
      searchForm: {
        diagnosisItemName: "",     // 名称
        diagnosisItemId: "",       // 诊断项名称id
        diagnosisItemSymbolNo: "", // 编号
      },
      // 表格
      propList: [
        { prop: "diagnosisItemName", label: "诊断项名称", minWidth: "120" },
        { prop: "diagnosisItemSymbolNo", label: "诊断项症状编号", minWidth: "120", },
        { prop: "diagnosisItemSymbolDesc", label: "特征描述", minWidth: "120" },
        { label: "特征图片", minWidth: "120", slotName: "featureImage" },
        { label: "操作", minWidth: "180", slotName: "operation" },
      ],
      tableData: [],       // 表格数据
      idList: [],          // 表格所选行的id数组，用于批量删除；
      labelWidth: "100px", // 表单项宽度
      // 分页
      total: 1,       // 总条数
      currentPage: 1, // 当前页
      pageSize: 10,   // 每页条数
      // 对话框-添加/编辑表单收集
      toForm: {
        diagnosisItemName: "",         // 名称
        diagnosisItemId: "",           // 诊断项名称id
        diagnosisItemSymbolNo: "",     // 编号
        diagnosisItemSymbolDesc: "",   // 描述
        fileIdList: "",                // 表单图片id集合
      },
      fileIdList: [],                  // 本地图片id集合
      fileList: [],          // 修改-图片回显集合
      MyHeader: "",          // 图片请求头
      dialogImageUrl: "",    // 添加/修改 - 大图预览url
      dialogVisible: false,  // 添加/修改 - 大图预览弹出框
      // 查看特征图片列
      featureImage: false,   // 查看特征图片 - dialog
      imageList: [],         // 查看特征图片 - url集合
      boxWidth: "",          // 弹出框自适应-图片宽度
      dialogWidth: "",       // 弹出框自适应-dialog宽度
      // 其它
      title: "添加",
      formLabelWidth: "160px",         // el-form-item宽度
      diagnosisItemName: [],           // 诊断项名称
      dialogFormVisible: false,        // 添加/编辑-对话框显示/隐藏
      // 表单验证
      rules: {
        diagnosisItemId: [
          { required: true, message: "请选择", trigger: ["blur"] },
        ],
        diagnosisItemSymbolNo: [
          { required: true, message: "请输入", trigger: ["blur"] },
        ],
        diagnosisItemSymbolDesc: [
          { required: true, message: "请输入", trigger: ["blur"] },
        ],
        // fileId:[
        //   { required: true,validator: validateAttach, trigger: ["blur",'change'] },
        // ],
      },
    };
  },
  created() {
    this.getDiagnosisSymptomList();  // 诊断项症状
    this.getDiagnosisList();         // 诊断项
  },
  mounted() {
    let token = getCookie("token");
    this.MyHeader = { Satoken: token };
    console.log("this.MyHeader", this.MyHeader);
  },
  methods: {
    // 查询
    search() {
      this.currentPage = 1;
      this.getDiagnosisSymptomList();
    },
    // 获取诊断项症状
    async getDiagnosisSymptomList() {
      let params = {
        page: this.currentPage, // 当前页
        size: this.pageSize,    // 每页条数
        condition: this.searchForm,
      };
      let res = await DiseaseFeaturesManageApi.queryPageByCondition(params);
      console.log("诊断项症状", res);
      if (res.code == 200) {
        this.tableData = res.data.content;
        this.total = res.data.totalElements;
      } else {
        this.$message.error(res.code);
      }
      console.log("res***", res);
    },
    // 获取诊断项名称
    async getDiagnosisList() {
      let res = await FeaturesTypeManageApi.queryByCondition();
      console.log("获取诊断项名称", res.data);
      this.diagnosisItemName = res.data;
      console.log("this.diagnosisItemName", this.diagnosisItemName);
    },
    // 当前页
    handleCurrentChange(e) {
      this.currentPage = e;
      this.getDiagnosisSymptomList();
      console.log(`当前第${e}页`);
    },
    //
    handleSizeChange(e) {
      this.pageSize = e;
    },
    // 添加
    add() {
      console.log(this.tableData);
      this.title = "添加";
      this.dialogFormVisible = true;
      this.toForm = {};
    },
    // 修改
    edit(row) {
      console.log(row);
      this.title = "修改";
      this.dialogFormVisible = true;
      this.toForm = { ...row };
      // 图片回显
      this.fileIdList = row.fileIdList.split(",");  
      this.fileIdList.forEach((item) => {           
        // 下载当前行图片
        newDocumentApi.fileDownload({ fileId: item }).then((res) => {
          blobToBase64(res).then((imageUrl) => { 
            this.fileList.push({   
              url: imageUrl,  
              fileId: item,   
            });
          });
        });
      });
    },
    // 图片上传成功回调
    onSuccessImg(res, file, fileList) {
      if (res.code == 200) {
        this.fileIdList.push(res.data);   
        this.$message.success("上传成功");
        return file.url;
      } else {
        this.$message.error("上传失败，请稍后再试");
      }
    },
    // 图片删除时回调
    handleRemove(file, fileList) {
      if (this.title == "添加") {
        this.fileIdList = fileList.map((item) => {
          return item.response.data;
        });
      } else { // 编辑操作时
        this.fileIdList = fileList.map((item) => {
          return item.fileId || item.response.data;
        });
      }
    },
    // 表格项 - 查看特征图片
    rowimg(fileId) {
      this.imageList = [];  
      if (!fileId) {
        this.$message("无上传图片！");
        return;
      }
      let fileIdList = fileId.split(",");
      fileIdList.map((item) => {
        newDocumentApi.fileDownload({ fileId: item }).then((res) => {
            blobToBase64(res).then((url) => {
              this.imageList.push(url);
            });
          })
        this.featureImage = true;
      });
    },
    // 图片自适应dialog
    onLoadImg(e) {
      var img = e.target;
      var width = 0;
      if (img.fileSize > 0 || (img.width > 1 && img.height > 1)) {
        width = img.width;
      }
      if (img.height > img.width && width > 370) {
        width = 370; // 这一步是定义了纵向图片的最大宽；
      } else if (width > 600) {
        width = 600; // 这一步是定义了非纵向的最大宽度；
      }
      this.boxWidth = width + "px"; // 图片的宽度
      this.dialogWidth = width + 40 + "px"; // dialog的宽度
    },
    // 对表单图片fileId字段手动进行表单验证
    handleChange(file, fileList) {
      this.$refs.ruleForm.validateField("fileId");
    },
    // 对话框 - 添加/修改表单
    save() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.title === "添加") {
            this.toForm.fileIdList = this.fileIdList.join(",");
            let res = await DiseaseFeaturesManageApi.add(this.toForm);
            if (res.code == 200) {
              this.$message.success("添加成功！");
              this.getDiagnosisSymptomList();
              this.dialogFormVisible = false; // 关闭对话框
            } else {
              this.$message.error(res.msg);
            }
          }
          if (this.title === "修改") {
            this.toForm.fileIdList = this.fileIdList.join(",");
            let res = await DiseaseFeaturesManageApi.edit(this.toForm);
            if (res.code == 200) {
              this.$message.success("修改成功！");
              this.getDiagnosisSymptomList();
              this.dialogFormVisible = false; // 关闭对话框
            } else {
              this.$message.error(res.msg);
            }
          }
        } else {
          return false;
        }
      });
    },
    // 删除单条数据
    del(row) {
      console.log("当前删除的", row);
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await DiseaseFeaturesManageApi.delById(
            row.diagnosisItemSymbolId
          );
          console.log("---", res);
          if (res.code == 200) {
            if (this.total % this.pageSize == 1 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.getDiagnosisSymptomList();
            this.$message({ type: "success", message: "删除成功!" });
          } else {
            this.$message.error(res.code);
          }
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
    // 当表格的选择项发生变化时触发
    handleSelectionChange(selectData) {
      this.idList = [];
      selectData.forEach((item) => {
        item.diagnosisItemSymbolId &&
          this.idList.push(item.diagnosisItemSymbolId);
        console.log("当前的item", item);
      });
      console.log("this.idList", this.idList);
    },
    // 批量删除
    delSelectData() {
      if (!this.idList.length) {
        return;
      }
      this.$confirm("您确定删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          DiseaseFeaturesManageApi.delListById(this.idList).then((res) => {
            if (res.code == 200) {
              this.getDiagnosisSymptomList();
              this.$message({ type: "success", message: "删除成功!" });
            } else {
              this.$message.error(res.code);
            }
          });
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
    // 取消按钮
    cancle() {
      this.dialogFormVisible = false;
      this.fileIdList = [];
      this.fileList = [];
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
      });
      this.$refs.upload.clearFiles();
    },
    // 添加/修改-大图预览on-preview
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
// dialog框header背景色
::v-deep .el-dialog__header {
  background: #0480fb;
}
// 设置dialog框叉号颜色
::v-deep .el-dialog__close {
  color: #fff;
}
// dialog框标题颜色
::v-deep .el-dialog__title {
  color: #fff;
}
::v-deep .aTextarea {
  width: 100%;
}
::v-deep .aTextarea > :nth-child(2) {
  width: 100%;
}
/* 特征图片-对话框 */
::v-deep .tzImg {
  .el-form-item__content {
    display: flex;
    > div:nth-child(1) {
      margin-top: 32px;
      margin-right: 50px;
    }
    .ppp {
      width: 148px;
      height: 148px;
      background: #000;
    }
  }
}
/* 特征描述文本域 */
::v-deep .el-textarea {
  position: relative;
  /* 特征描述文本域-文本框 */
  .el-textarea__inner {
  }
  /* 特征描述文本域-限制字数 */
  .el-input__count {
    position: absolute;
    bottom: -20px;
    line-height: 12px;
  }
}
.image-item {
  width: 100px;
  margin-right: 10px;
}
</style>
<style>
/* 图片上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
